package pers.vic.boot.security.data.interceptor;

import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlCommandType;
import org.apache.ibatis.plugin.*;
import pers.vic.boot.base.model.BaseEntity;
import pers.vic.boot.security.jwt.AuthorityInfo;

import java.util.Date;
import java.util.Properties;

/**
 * 描述: 在新增或修改的时候追加通用字段
 * @author Vic.xu
 * @date 2022-03-02 9:29
 */
@Intercepts(@Signature(type = Executor.class, method = "update", args = {MappedStatement.class, Object.class}))
public class CommonFieldInterceptor implements Interceptor {

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        fillCommonField(invocation);
        return invocation.proceed();
    }

    @Override
    public Object plugin(Object target) {
        return Plugin.wrap(target, this);
    }

    @Override
    public void setProperties(Properties properties) {

    }

    /**
     * 追加通用字段
     * @param invocation
     */
    private void fillCommonField(Invocation invocation) {
        //Executor的update  方法有两个参数
        Object[] args = invocation.getArgs();
        MappedStatement ms = (MappedStatement) invocation.getArgs()[0];
        SqlCommandType sqlCommandType = ms.getSqlCommandType();
        Object parameter = invocation.getArgs()[1];

        switch (sqlCommandType) {
            case UPDATE:
                fillUpdateCommonField(parameter);
                break;
            case INSERT:
                fillInsertCommonField(parameter);
                break;
            default:
                break;
        }

    }

    private void fillInsertCommonField(Object parameter) {
        if (parameter instanceof BaseEntity) {
            BaseEntity model = (BaseEntity) parameter;


            model.setCreateTime(new Date());
            model.setUpdateTime(new Date());
            AuthorityInfo authrityInfo = RowDataHelper.getAuthrityInfo();
            if (authrityInfo != null) {
                //创建人和修改人
            }


        }
    }

    private void fillUpdateCommonField(Object parameter) {

        if (parameter instanceof BaseEntity) {
            BaseEntity model = (BaseEntity) parameter;
            model.setUpdateTime(new Date());
            AuthorityInfo authrityInfo = RowDataHelper.getAuthrityInfo();
            if (authrityInfo != null) {
                //修改人
            }


        }
    }
}
